package com.frogs.ucenter.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.frogs.framework.base.web.BaseController3;
import com.frogs.framework.util.DWZResponse;
import com.frogs.framework.util.PageList;
import com.frogs.framework.util.RenderUtil;
import com.frogs.framework.util.StringUtil;
import com.frogs.framework.util.date.DateUtil;
import com.frogs.framework.web.HttpRequestInfo;
import com.frogs.system.util.UserAccountInfoStatusEnum;
import com.frogs.ucenter.entity.UserAccountInfo;
import com.frogs.ucenter.entity.UserBaseAccountInfo;
import com.frogs.ucenter.entity.UserBaseInfo;
import com.frogs.ucenter.service.UserAccountInfoService;
import com.frogs.ucenter.service.UserBaseInfoService;
import com.frogs.ucenter.service.UserLevelInfoService;

@Controller
@RequestMapping("/admin/user/accountInfo")
public class UserAccountInfoController extends BaseController3 {
    private static final String ROOT_VIEW = "/admin/userInfo";

    private static final String HOME_VIEW = ROOT_VIEW + "/home";
    
    private static final String LOOKUP_VIEW = ROOT_VIEW + "/lookup";

    private static final String EDIT_VIEW = ROOT_VIEW + "/edit";

    @Resource
    private UserAccountInfoService userAccountInfoService;
    @Resource
    private UserBaseInfoService userBaseInfoService;
    @Resource
    private UserLevelInfoService userLevelInfoService;

    @RequestMapping()
    public String listUserAccountInfo(HttpServletRequest request, ModelMap model, @Param(value="oper") String oper) {
    	HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        setRequestModelMap( request, model, true );
        model.put("orderByClause", "a.create_time desc");
        if(!StringUtil.isEmpty(reqInfo.getParameter("gtCreateDate"))) {
        	String gtCreateDate = String.valueOf(reqInfo.getParameter("gtCreateDate"));
        	model.put("gtCreateTime", DateUtil.parseDate(gtCreateDate).getTime());
        }
        
        String ltCreateDate = reqInfo.getParameter("ltCreateDate"); 
        if(!StringUtil.isEmpty(ltCreateDate)) {
        	model.put("ltCreateTime", DateUtil.parseDate(ltCreateDate).getTime());
        }
        
        if (!StringUtil.isEmpty(reqInfo.getParameter("eqPhone"))) {
        	model.put("eqIsPhoneValid", UserAccountInfoStatusEnum.AVAILABILITY_YES.getId());
        }
        if (!StringUtil.isEmpty(reqInfo.getParameter("eqEmail"))) {
        	model.put("eqIsEmailValid", UserAccountInfoStatusEnum.AVAILABILITY_YES.getId());
        }
        
        getPageList( model );
        if(!StringUtil.isEmpty(oper) && "lookup".equalsIgnoreCase(oper)) {
        	return LOOKUP_VIEW;
        }
        return HOME_VIEW;
    }

    @RequestMapping(EDIT)
    public String createUserAccountInfo(HttpServletRequest request, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        setRequestModelMap( request, model, false );
        Integer id = reqInfo.getIntParameter( "id", -1 );
        if( id > 0 ){
            model.put( "account",userAccountInfoService.getById( id ) ); 
            model.put( "userInfo",userBaseInfoService.getById( id ) ); 
            model.put("levelInfo", userLevelInfoService.getById(id));
        }
        model.put("parentRel", model.get("rel"));
        return EDIT_VIEW;
    }

    @RequestMapping(ADD)
    public String saveUserAccountInfo(HttpServletRequest request, HttpServletResponse response, ModelMap model, UserAccountInfo userAccountInfo) {
        setRequestModelMap(request, model, false);
        DWZResponse.Builder builder;
        try {
            userAccountInfoService.insert( userAccountInfo ); 
            builder = DWZResponse.getSucessBuilder("添加成功");
            builder.navTabId(String.valueOf(model.get("parentRel")));
            builder.callbackType("closeCurrent");
            builder.forwardUrl("/admin/user/accountInfo");
        } catch (Exception e) {
            builder = DWZResponse.getFailBuilder("fail" + e.getMessage());
        }
        
        RenderUtil.renderHtml(builder.build().toString(), response);
        return null;
    }

    @RequestMapping(UPDATE)
    public String updateUserAccountInfo(HttpServletRequest request, HttpServletResponse response, ModelMap model, UserAccountInfo userAccountInfoNew) throws Exception {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        Integer id = reqInfo.getIntParameter( "id", -1 );
        if( id > 0 ){
            DWZResponse.Builder builder;
            try {
            	
                UserAccountInfo userAccountInfo = userAccountInfoService.getById( id ); 
                Map<String,Object> param = new HashMap<String,Object>();
                
                String accountName = reqInfo.getParameter("accountName");
                if(!StringUtil.isEmpty(accountName)) {
                	userAccountInfo.setAccountName(accountName);
                }
                
                String email = reqInfo.getParameter("email");
                
                if(!StringUtil.isEmpty(email)) {
                	param.clear();
                	param.put("eqEmail", email);
                	param.put("eqIsEmailValid", 1);
                	List<UserAccountInfo> users = userAccountInfoService.getList(param, 1, 20);
                	if(users.size() >= 2) {
                		throw new Exception("该号码已被绑定过!");
                	}
                	if(users.size() == 1) {
                		if(!users.get(0).getId().equals(id)) {
                			throw new Exception("该号码已被绑定过!");
                		}
                	}
                	
                	userAccountInfo.setEmail(email);
                }
                
                int isEmailValid = reqInfo.getIntParameter("isEmailValid",0);
                userAccountInfo.setIsEmailValid(isEmailValid);
                
                String phone = reqInfo.getParameter("phone");
                int isPhoneValid = reqInfo.getIntParameter("isPhoneValid",0);
                
                if(!StringUtil.isEmpty(phone)) {
                	param.clear();
                	param.put("eqPhone", phone);
                	param.put("eqIsPhoneValid", 1);
                	List<UserAccountInfo> users = userAccountInfoService.getList(param, 1, 20);
                	if(users.size() >= 2) {
                		throw new Exception("该号码已被绑定过!");
                	}
                	if(users.size() == 1) {
                		if(!users.get(0).getId().equals(id)) {
                			throw new Exception("该号码已被绑定过!");
                		}
                	}
                	
                	userAccountInfo.setPhone(phone);
                }
                
                userAccountInfo.setIsPhoneValid(isPhoneValid);
                
                userAccountInfoService.update( userAccountInfo );
                
                UserBaseInfo userBase = userBaseInfoService.getById(id);
                String nickName = reqInfo.getParameter("nickName");
                userBase.setNickName(nickName);
                param.clear();
            	param.put("eqNickName", nickName);
            	List<UserBaseInfo> users = userBaseInfoService.getList(param, 1, 20);
            	if(users.size() >= 2) {
            		throw new Exception("该昵称不可用!");
            	}
            	if(users.size() == 1) {
            		if(!users.get(0).getId().equals(id)) {
            			throw new Exception("该昵称不可用!");
            		}
            	}
                
                int sex = reqInfo.getIntParameter("sex", 1);
                userBase.setSex(sex);
                
                int age = reqInfo.getIntParameter("age", 0);
                userBase.setAge(age);
                
                int identityType = reqInfo.getIntParameter("identityType", 1);
                userBase.setIdentityType(identityType);
                
                String identityCard = reqInfo.getParameter("identityCard");
                if(StringUtil.isEmpty(identityCard)) {
                	userBase.setIdentityCard(identityCard);
                }
                
                String emergencyContactName = reqInfo.getParameter("emergencyContactName");
                userBase.setEmergencyContactName(emergencyContactName);
                
                String emergencyPhone = reqInfo.getParameter("emergencyPhone");
                userBase.setEmergencyPhone(emergencyPhone);
                
                String medicalInsuranceInfo = reqInfo.getParameter("medicalInsuranceInfo");
                userBase.setMedicalInsuranceInfo(medicalInsuranceInfo);
                
                userBaseInfoService.update(userBase);
                
                model.clear();
                builder = DWZResponse.getSucessBuilder("修改成功!");
                builder.navTabId(String.valueOf(model.get("parentRel")));
                builder.callbackType("closeCurrent");
                builder.forwardUrl("/admin/user/accountInfo");
            } catch (Exception e) {
                builder = DWZResponse.getFailBuilder(e.getMessage());
            }
            RenderUtil.renderHtml(builder.build().toString(), response);
        }
        return null;
    }

    @RequestMapping(DELETE)
    public String deleteUserAccountInfo(HttpServletRequest request, HttpServletResponse response, ModelMap model, String inIdList) {
        setRequestModelMap(request, model);
        DWZResponse.Builder builder;
        try {
            String[] idArray = inIdList.split(",");
            model.put("inIdList", idArray);
            userAccountInfoService.delete( model ); 
            builder = DWZResponse.getSucessBuilder("删除成功");
        } catch (Exception e) {
            builder = DWZResponse.getFailBuilder("操作失败" + e.getMessage());
        }
        RenderUtil.renderHtml(builder.build().toString(), response);
        model.clear();
        return null;
    }

    private PageList<UserBaseAccountInfo> getPageList(ModelMap model) {
        PageList<UserBaseAccountInfo> userAccountInfoList = userAccountInfoService.listBaseAccount( model, Integer.parseInt(model.get("pageNum").toString()), Integer.parseInt(model.get("numPerPage").toString()) ); 
        model.put("userBaseAccountInfoList",userAccountInfoList);
        model.put("pageTurn",userAccountInfoList.getPageTurn());
        return userAccountInfoList;
    }
}